﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace TheGunningMan
{
    namespace Core
    {
        internal class BulletScript : IDisposable
        {
            [DllImport("BulletScriptWrapper.dll")] static extern int createMachine();
            [DllImport("BulletScriptWrapper.dll")] static extern void destroyMachine(int id);
            [DllImport("BulletScriptWrapper.dll", CharSet = CharSet.Ansi)] static extern bool compileScript(int id, string script, int len);
            [DllImport("BulletScriptWrapper.dll")] static extern void update(int id, float dt);
            
            private int id;

            /// <summary>
            /// Constructor.
            /// </summary>
            public BulletScript()
            {
                this.id = createMachine();
            }

            /// <summary>
            /// Destructor.
            /// </summary>
            ~BulletScript()
            {
                Dispose();
            }

            /// <summary>
            /// Compile script in a filename.
            /// </summary>
            /// <param name="filename">filename to compile.</param>
            /// <returns>true if no errors, otherwise false.</returns>
            bool Compile(string filename)
            {
                string text = File.ReadAllText(filename);
                return compileScript(this.id, text, text.Length);
            }

            /// <summary>
            /// Update VM.
            /// </summary>
            /// <param name="dt">time since last update.</param>
            void Update(float dt)
            {
                update(this.id, dt);
            }

            #region IDisposable implementation

            bool _disposed = false;

            public void Dispose()
            {
                if (!this._disposed)
                {
                    destroyMachine(this.id);
                    this._disposed = true;
                }
            }

            #endregion
        }
    }
}
